<script lang="ts" setup>
// import type { CompanyVO } from '#/api/company/manage/model';

import { computed, defineComponent, onMounted, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, message, Select, Spin } from 'ant-design-vue';
import { debounce } from 'lodash-es';

import { companyInfo, companyList } from '#/api/company/manage';

import tycCompanySelectModal from './components/tyc-company-select-modal.vue';

interface Props {
  showTycButton?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  showTycButton: false,
});

const emit = defineEmits(['blur', 'change', 'select']);
const loading = ref(false);
// const isLoaded = ref(false);
const showDropOptions = ref<any>(undefined);
const showDropOptionsComp = computed(() => {
  return props.showTycButton ? showDropOptions.value : undefined;
});
const notFoundContent = ref<any>(null);
const currSearchName = ref('');
const showMore = ref(false); // 显示查看更多按钮
const list = ref<any[]>([]);
const currListCache = ref<any[]>([]);
const modelValue = defineModel<number | string>('value', {
  default: () => undefined,
});

watch(
  () => modelValue.value,
  async (newVal) => {
    if (newVal) {
      const company = await companyInfo(newVal);
      if (company) {
        list.value = [{ value: company.id, label: company.name }];
        currListCache.value = [{ value: company.id, label: company.name }];
      }
    }
  },
  { immediate: true },
);

const getCompanyList = debounce(async (name: string) => {
  currSearchName.value = name;
  if (!name) return;
  list.value = [];
  // console.log('搜索公司名：', name);
  loading.value = true;

  const results = (await companyList({ name, pageSize: 10 })) ?? [];
  if (currSearchName.value === name) {
    list.value = results.map((item) => {
      return { label: item.name, value: item.id };
    });
    notFoundContent.value = results?.length > 0 ? null : '没有查到企业信息';
    showMore.value = true;
  }
  loading.value = false;
}, 300);

async function handleSearch(val: string) {
  if (!val) return;
  console.log(val);
  await getCompanyList(val);
}

async function handleChange(val: any) {
  console.log(val);
  currSearchName.value = getCompanyName(val);
  emit('change', modelValue.value);
}

function getCompanyName(id: string) {
  const target = list.value.find((item) => item.value === id);
  return target?.label || null;
}

async function handleSelect(val: any, option: any) {
  showMore.value = false;
  console.log(val, option);
  if (option.tyc) {
    // 选择的是天眼查的新企业
  }
  emit('select', val);
}

function handleBlur() {
  emit('blur');
  if (props.showTycButton) {
    showDropOptions.value = undefined;
    list.value = [...currListCache.value];
    showMore.value = false;
    currSearchName.value = '';
  }
}

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});

// 从天眼查查询更多公司
// async function searchTycMore(e: any) {
//   e.preventDefault();
//   loading.value = true;
//   console.log(modelValue.value, currSearchName.value);
//   setTimeout(() => {
//     list.value.push({ label: '新增的测试公司', value: Date.now(), tyc: true });
//     loading.value = false;
//   }, 300);
// }

const [TycCompanySelectModal, tycCompanySelectModalApi] = useVbenModal({
  connectedComponent: tycCompanySelectModal,
  onOpenChange: (isOpen) => {
    if (!isOpen) {
      showDropOptions.value = true;
    }
  },
});

function showAdd() {
  showDropOptions.value = false;
  tycCompanySelectModalApi.open();
}

function addCompanySuccess(data: any) {
  console.log(data);
  if (data?.name) {
    message.success('新增成功，请重新搜索选择');
  }
  showDropOptions.value = true;
}

onMounted(async () => {
  //
});
</script>
<template>
  <Select
    v-model:value="modelValue"
    class="w-full"
    :open="showDropOptionsComp"
    placeholder="从企业数据库搜索公司"
    show-search
    :show-arrow="false"
    :filter-option="false"
    :default-active-first-option="false"
    :not-found-content="loading ? undefined : notFoundContent"
    :options="list"
    :label-in-value="false"
    @change="handleChange"
    @search="handleSearch"
    @select="handleSelect"
    @blur="handleBlur"
  >
    <template v-if="loading" #notFoundContent>
      <!--<Spin size="small" />-->
    </template>
    <template #dropdownRender="{ menuNode: menu }">
      <Spin :spinning="loading">
        <VNodes :vnodes="menu" />
      </Spin>
      <Button
        v-if="showTycButton && showMore"
        block
        class="mt-[5px]"
        type="dashed"
        @click="showAdd"
      >
        找不到“{{ currSearchName }}”？去新增
      </Button>
    </template>
  </Select>
  <TycCompanySelectModal v-if="showTycButton" @reload="addCompanySuccess" />
</template>
